<template>
    <el-dialog :visible="visibleTree" :center="true" width="460px" :before-close="handleClose">
        <span slot="title">修改角色</span>
        <el-tree :data="options" show-checkbox ref="tree" node-key="id" :default-expanded-keys="expandedKeys" :default-checked-keys="checkedKeys" :props="defaultProps">
        </el-tree>
        <el-button type="primary" @click="submitForm">保存</el-button>
    </el-dialog>
</template>

<script>
import { userRights, allRights } from '@/api/http';
export default {
    name: 'tableTree',
    props: { visibleTree: Boolean, userInfo: Object },
    data() {
        return {
            options: [],
            defaultProps: {
                children: 'children',
                label: 'authName'
            },
            labelPosition: 'right',
            expandedKeys: [],
            checkedKeys: []
        }
    },
    mounted() {
        this.init()
    },
    watch: {
        visibleTree: {
            handler(val) {
                if (val) {
                    this.expandedKeys = []
                    this.checkedKeys = []
                    this.filter(this.userInfo.children)
                }
            }
        }
    },
    methods: {
        filter(arr) {
            arr.forEach((el) => {
                if (el.children?.length > 0) {
                    this.filter(el.children)
                } else {
                    this.expandedKeys.push(el.id)
                    this.checkedKeys.push(el.id)
                }
            })
        },
        async init() {
            const { data, meta } = await allRights('tree')
            if (meta.status == 200) {
                this.options = data
            }
        },
        // 关闭弹窗
        handleClose() {
            const nodes = this.$refs.tree.store._getAllNodes()
            // 或者方法二
            // const nodes = this.$refs.tree.store.nodesMap
            for (let i in nodes) {
                nodes[i].expanded = false
            }
            this.$refs.tree.setCheckedKeys([])
            this.updateVisible(false)
        },
        // 提交
        submitForm() {
            const arr = [...new Set(this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys()))].toString()
            this.addRoles(arr)
        },
        // 角色授权
        async addRoles(arr) {
            const { data, meta } = await userRights(this.userInfo.id, { rids: arr })
            if (meta.status == 200) {
                this.$message.success(this.$t('message.updeteSuccess'))
                this.handleClose()
                this.$emit('done')
            }
        },
        /* 更新visible */
        updateVisible(value) {
            this.$emit("update:visibleTree", value);
        },
    },
}
</script>

<style lang="scss" scoped>
</style>